package com.example.blog.controller;

import com.example.blog.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Annotation;


@Component
@ControllerAdvice
public class LoginAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        RequestMapping methodAnnotation =
                returnType.getMethodAnnotation(RequestMapping.class);
        if (methodAnnotation != null && methodAnnotation.value().length >0) {
            if ("login".equals(methodAnnotation.value()[0])) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ServletServerHttpRequest req = (ServletServerHttpRequest) request;
        ServletServerHttpResponse resp = (ServletServerHttpResponse) response;
        HttpSession session = req.getServletRequest().getSession();
        User myinfo = (User) session.getAttribute("myinfo");
        if (myinfo != null) {
            Cookie cookie = new Cookie("uid", myinfo.getId().toString());
            //有效期一周
            cookie.setMaxAge(60 * 60 * 24 * 7);
            resp.getServletResponse().addCookie(cookie);
        }
        return body;
    }
}
